<?php
class admin_log_controller extends common {
	const fields = array('aid' => '管理员', 'module' => '模块', 'action' => '操作内容', 'ip' => 'ip地址', 'time' => '记录时间');
	function log_list() {
		if (!isset($_POST['page']) || !is_numeric($_POST['page']) || $_POST['page'] < 1)
			$_POST['page'] = $this->def_page;
		
		if (!isset($_POST['limit']) || !is_numeric($_POST['limit']) || $_POST['limit'] < 1)
			$_POST['limit'] = $this->def_limit;
		
		$limit     = 'ORDER BY a.`time` DESC LIMIT ' . ($_POST['page'] - 1) * $_POST['limit'] . ', ' . $_POST['limit'];
		$tableName = 'admin_log';
		
		filter_post(self::fields, true);
		
		$wheres = array();
		foreach ($_POST as $key => $value) {
			if ($key === 'time' && preg_match('/^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(2[0-3]|[0-1]\d):[0-5]\d:[0-5]\d$/', $value))
				$wheres[] = "a.`{$key}` >= '{$value}'";
			else if ($key === 'aid')
				$wheres[] = "IFNULL(b.`name`, b.`user`) LIKE '{$value}'";
			else
				$wheres[] = "a.`{$key}` LIKE '%{$value}%'";
		}
		$where = count($wheres) > 0 ? 'WHERE ' . implode(' AND ', $wheres) : '';
		
		$sql = trim('
			SELECT %1$s
			FROM `%2$s` a
			LEFT JOIN `%3$s` b ON a.`aid` = b.`id`
			%4$s
			%5$s
		');
		
		if (false === $rows = $this->sql->doSql(sprintf($sql, "a.*, b.`name` AS `name`, b.`user` AS `user`", $tableName, 'admin_user', $where, $limit)))
			return msg(1, '获取数据失败！');
		
		return msg(0, null, array(
			'count' => ($row = $this->sql->doSql(sprintf($sql, "COUNT(*) AS `count`", $tableName, 'admin_user', $where, ''), false)) ? $row['count'] : 0,
			'data' => $rows
		));
	}
	
	// 删除
	function delete() {
		$tableName = 'admin_log';
		
		if (!empty($_POST['id'])) {
			if (!preg_match('/^\s*\d+\s*(,\s*\d+\s*)*$/', $_POST['id']))
				return msg(1, '参数非法！');
			else if (!$res = $this->sql->where("`id` IN ({$_POST['id']})")->delete($tableName))
				return msg(2, '删除失败！');
		}

		if (!$res = $this->sql->where("1=1")->delete($tableName))
			return msg(3, '删除失败！');
		
		$this->sql->increment($tableName);
		if (empty($_POST['id']))
			$this->log('清空日志');
		
		return msg(0,  "成功删除{$res}条日志！");
	}
}